from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants
from info import db
from info.models import News, Category
from info.utils.commons import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import profile_blue


# 请求路径: /user/pic_info
# 请求方式:GET,POST
# 请求参数:无, POST有参数,avatar
# 返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
@profile_blue.route('/pic_info',methods=['GET', 'POST'])
@user_login_data
def pic_info():
    # 判断请求方式
    if request.method == "GET":
        # # 获取用户头像信息
        # avatar_url = g.user.avatar_url
        # # 拼接数据
        # data = {
        #     "avatar_url":avatar_url
        # }
        # 携带数据，渲染页面
        return render_template("news/user_pic_info.html",user = g.user.to_dict())
        # pass

    # 获取参数
    avatar = request.files.get("avatar")

    # 校验参数
    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 上传图片，判断是否成功
    try:
        image_namge = image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云异常")

    # 校验图片是否为空
    if not image_namge:return jsonify(errno=RET.NODATA, errmsg="图片上传失败")

    # 设置图片到用户对象
    g.user.avatar_url = image_namge

    data = {
        "avatar_url":constants.QINIU_DOMIN_PREFIX + image_namge
    }

    return jsonify(errno=RET.OK, errmsg="成功",data = data)


# 获取/设置,新闻发布
# 请求路径: /user/news_release
# 请求方式:GET,POST
# 请求参数:GET无, POST ,title, category_id,digest,index_image,content
# 返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
@profile_blue.route('/news_release', methods=['GET', 'POST'])
def news_release():

    # 判断请求方式
    if request.method == "GET":
        # 获取分类信息
        try:
            category = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取分类失败")

        # 获取分类列表
        category_list = []
        for cate in category:
            category_list.append(cate.to_dict())

        return render_template("news/user_news_release.html",category_list = category_list)



    # 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("content")

    # 校验参数，为空校验
    if not all[title,category_id,digest,content,index_image]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 创建新闻对象，设置属性
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.index_image_url = "器牛云前缀地址"+index_image

    db.session.add(news)
    db.session.commit()


    return render_template("news/user_news_release.html")

#
# 用户新闻列表
# 请求路径: /user/news_list
# 请求方式:GET
# 请求参数:p
# 返回值:GET渲染user_news_list.html页面
@profile_blue.route('/news_list')
@user_login_data
def news_list():

    # 获取参数
    page = request.args.get("p","1")

    # 转换类型
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 获取用户发布新闻的分页对象
    try:
        paginate = g.user.news_list.order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 获取分页数据
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    #  获取用户发布新闻列表
    news_list = []
    for new in items:
        news_list.append(new.to_dict())


    # 拼接数据
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }


    return render_template("/news/user_news_list.html", data = data)

# 获取新闻收藏列表
# 请求路径: /user/ collection
# 请求方式:GET
# 请求参数:p(页数)
# 返回值: user_collection.html页面
@profile_blue.route("/collection")
@user_login_data
def collection():
    # 获取参数
    page = request.args.get("page",1)

    # 装换类型，用于分页查询
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
    # 获取用户收藏的所有新闻
        paginate = g.user.collection_news.order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")

    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    # 新闻对象转换成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    data = {
        "total_page":total_page,
        "curren_tpage":current_page,
        "news_list":news_list
    }

    return render_template("news/user_collection.html", data = data)


# 获取/设置用户密码
# 请求路径: /user/pass_info
# 请求方式:GET,POST
# 请求参数:GET无, POST有参数,old_password, new_password
# 返回值:GET请求: user_pass_info.html页面,data字典数据, POST请求: errno, errmsg

@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    # 判断请求方式
    if request.method == "GET":
        # # 判断用户是否登录,实现修改密码完成后的登出功能
        # if not g.user:
        #     return redirect("/")
        return render_template("news/user_pass_info.html")

    # 获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 参数为空校验
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 校验原始密码
    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="原始密码错误")

    # 修改密码
    g.user.password = new_password

    # 清楚用户登录信息
    session.pop("user_id",None)
    session.pop("nick_name",None)
    session.pop("mobile",None)

    return jsonify(errno=RET.OK, errmsg="修改密码成功")

# 获取/设置用户基本信息
# 请求路径: /user/base_info
# 请求方式:GET,POST
# 请求参数:POST请求有参数,nick_name,signature,gender
# 返回值:errno,errmsg
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():

    # 判断请求方式
    if request.method == "GET":
        return render_template("news/user_base_info.html", user=g.user.to_dict())


    # 获取参数
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    # 参数为空校验
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 验证性别
    if gender not in ["MAN","WOMAN"]:
        return jsonify(errno=RET.DATAERR, errmsg="性别异常")

    try:
        g.user.nick_name = nick_name
        g.user.signature = signature
        g.user.gender = gender
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="更改失败")


    return jsonify(errno=RET.OK, errmsg="修改成功")





# 获取用户信息首页
# 请求路径: /user/info
# 请求方式:GETs
# 请求参数:无
# 返回值: user.html页面,用户字典data数据

@profile_blue.route('/info')
@user_login_data
def user_info():
    # 判断用户是否登录
    if not g.user:
        return redirect("/")


    # 当前用户登录信息
    data = {
        "user_info": g.user.to_dict()
    }

    return render_template("news/user.html", data=data)


